import { h, onMounted, reactive, ref, toRaw } from "vue";
import type { PaginationProps } from "@pureadmin/table";
import type { FormItemProps } from "./types";
import { addDialog } from "@/components/ReDialog";
import { deviceDetection } from "@pureadmin/utils";
import editForm from "./form.vue";
import { message } from "@/utils/message";
import { ElMessageBox } from 'element-plus'
import { projectSelectApi } from '@/api/projectApi';
import { companySelectApi } from "@/api/quotedPriceApi";
import {
  productListApi,
  productShowApi,
  purchaseOrderListApi
} from "@/api/purchaseOrderApi";
export function useCorps() {
  const form = reactive({
    page: 1,
    perPage: 20,
    keyword: null,
    dateRange: null,
    purchaseOrderId: null,
    productName: null,
    productNo: null,
    categoryId: null,
    projectId: null,
    storeId: null,
    sortType: null,
    sortOrder: null,
    companyId: null
  });
  const formRef = ref();
  const dataList = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    background: true,
    pageSizes: [10,20,50,100]
  });
  const columns: TableColumnList = [
    // {
    //   label: "ID",
    //   prop: "productId",
    //   sortable: true,
    //   width: 70
    // },
    {
      label: "产品名称",
      prop: "productName",
      minWidth: 150,
    },
    {
      label: "产品编号",
      prop: "productNo",
      minWidth: 150,
    },
    {
      label: "规格",
      prop: "productSpec",
      minWidth: 150,
    },
    {
      label: "单位",
      prop: "productUnit",
      minWidth: 90,
    },
    {
      label: "数量",
      prop: "number",
      sortable: true,
      minWidth: 120,
      formatter:(row: any)=> {
        let number: any = row.number * 1
        return number;
      }
    },
    {
      label: "产品单价",
      prop: "price",
      sortable: true,
      minWidth: 140,
      formatter:(row: any)=> {
        let price: any = row.price * 1
        return price;
      }
    },
    {
      label: "总金额",
      prop: "amount",
      sortable: true,
      minWidth: 140,
      formatter:(row: any)=> {
        let amount: any = row.amount * 1
        return amount;
      }
    },
    {
      label: "分类",
      prop: "category.name",
      minWidth: 120,
    },
    {
      label: "项目",
      prop: "project.projectName",
      minWidth: 150,
    },
    {
      label: "仓库",
      prop: "store.name",
      minWidth: 150,
    },
    // {
    //   label: "设备",
    //   prop: "parts",
    //   formatter:(row: any)=> {
    //     let str = [];
    //     if(row.parts) {
    //       if(row.parts['1']) {
    //         for (let item of row.parts['1']) {
    //           str.push(item.deviceName ?? '--')
    //         }
    //       }
    //     }
    //     return str.length === 0 ? '--' : str.join();
    //   },
    //   minWidth: 150,
    // },
    // {
    //   label: "配件",
    //   prop: "parts",
    //   formatter:(row: any)=> {
    //     let str = [];
    //     if(row.parts) {
    //       if(row.parts['2']) {
    //         for (let item of row.parts['2']) {
    //           str.push(item.partName ?? '--')
    //         }
    //       }
    //     }
    //     return str.length === 0 ? '--' : str.join();
    //   },
    //   minWidth: 150,
    // },
    {
      label: "创建时间",
      prop: "createdAt",
      sortable: true,
      minWidth: 160
    },
    // {
    //   label: "更新时间",
    //   prop: "updatedAt"
    // },
    {
      label: "操作",
      fixed: "right",
      align: "center",
      slot: "operation",
      width: 80
    }
  ];
  function handleSizeChange(val: number) {
    form.page = 1;
    form.perPage = val;
    onSearch()
  }

  function handleCurrentChange(val: number) {
    form.page = val;
    onSearch()
  }

  async function onSearch() {
    loading.value = true;
    let params = {
      purchaseOrderId: form.purchaseOrderId,
      productName: form.productName,
      productNo: form.productNo,
      categoryId: form.categoryId,
      projectId: form.projectId,
      storeId: form.storeId,
      keyword: form.keyword,
      createdStartAt: form.dateRange ? form.dateRange[0] + ' 00:00:00' : null,
      createdEndAt: form.dateRange ? form.dateRange[1] + ' 23:59:59' : null,
      page: form.page,
      perPage: form.perPage,
      sortType: form.sortType,
      sortOrder: form.sortOrder,
      companyId: form.companyId
    }

    const res: any = await productListApi(cleanEmptyData(params));
    dataList.value = res?.result?.list;
    pagination.total = res?.result?.total;
    pagination.pageSize = res?.result?.perPage*1;

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  const resetForm = (formEl: any) => {
    if (!formEl) return;
    form.page = 1;
    form.keyword = null;
    form.dateRange = null;
    form.purchaseOrderId = null;
    form.productName = null;
    form.productNo = null;
    form.categoryId = null;
    form.projectId = null;
    form.storeId = null;
    form.sortType = null;
    form.sortOrder = null;
    form.companyId = null;
    formEl.resetFields();
    onSearch();
  };
  // 删除参数为空的键值
  function cleanEmptyData(obj: object) {
    Object.keys(obj).forEach(key => {
      if (obj[key] === null || obj[key] === '') {
        delete obj[key];
      }
    });
    return obj
  }
  async function openDialog(title = "创建设备", row?: FormItemProps) {
    const res: any = await productShowApi({
      productId: row.productId
    })
    let devArr = [];
    let partsArr = [];
    if(res?.result?.parts && res?.result?.parts['1']) {
      for (let item of res?.result?.parts['1']) {
        devArr.push(item.deviceName)
      }
    }
    if(res?.result?.parts && res?.result?.parts['2']) {
      for (let item of res?.result?.parts['2']) {
        partsArr.push(item.partName)
      }
    }
    let formInline = {
      title: title,
      productInfo: res?.result ?? {},
      devArr: devArr.join(),
      partsArr: partsArr.join(),
    };

    addDialog({
      title: `${title}`,
      props: {
        formInline: formInline
      },
      top: '5%',
      width: "800px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      hideFooter: true,
      contentRenderer: () => h(editForm, { ref: formRef }),

    });
  }
  const projectSelect = ref();
  const purchaseOrderSelect = ref();
  // 获取入库单
  const getPurchaseOrder = async(val?: any) => {
    if(val && val.length < 6) {
      return
    }
    const purchase: any = await purchaseOrderListApi({page: 1, perPage: 20, orderNo: val});
    purchaseOrderSelect.value = purchase?.result?.list;
  }
  const companySelect = ref()
  onMounted(async () => {
    onSearch();
    const project: any = await projectSelectApi({type: 'all'});
    projectSelect.value = project?.result;
    // 获取公司
    const company: any = await companySelectApi();
    companySelect.value = company?.result;
    // 获取入库单
    getPurchaseOrder()
  });
  function sortChange (column, prop, order) {
    form.sortOrder = "";
    if (column.order == "descending") {
      form.sortOrder = "desc";
      if (column.prop === "productId") {
        form.sortType = "id";
      } else if(column.prop === 'number') {
        form.sortType = "number";
      } else if(column.prop === 'createdAt') {
        form.sortType = "created_at";
      } else if(column.prop === 'price') {
        form.sortType = "price";
      } else if(column.prop === 'amount') {
        form.sortType = "amount";
      } else {
        form.sortType = column.prop;
      }
    } else if (column.order == "ascending") {
      form.sortOrder = "asc";
      if (column.prop === "productId") {
        form.sortType = "id";
      } else if(column.prop === 'number') {
        form.sortType = "number";
      } else if(column.prop === 'createdAt') {
        form.sortType = "created_at";
      } else if(column.prop === 'price') {
        form.sortType = "price";
      } else if(column.prop === 'amount') {
        form.sortType = "amount";
      } else {
        form.sortType = column.prop;
      }
    } else {
      form.sortOrder = "";
      form.sortType = "";
    }
    onSearch()
  }
  return {
    form,
    isShow,
    loading,
    columns,
    dataList,
    pagination,
    onSearch,
    resetForm,
    openDialog,
    handleSizeChange,
    handleCurrentChange,
    deviceDetection,
    projectSelect,
    sortChange,
    purchaseOrderSelect,
    getPurchaseOrder,
    companySelect
  };
}
